package com.leaves.common.util.docutil;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.IOUtils;

/**
 * @Author LEAVES
 * @Version 1.0
 * @Date 2023年07日27 00时14分07秒
 * @Description:
 */
public class WordTemplateWriter1 {

    public static void main(String[] args) {
        String templatePath = "D:\\Program Files (x86)\\app\\IDEA\\IDEA_WORKE\\sa-token-demo\\src\\main\\resources\\templates\\templates/日志.docx";
        String outputPath = "D:\\Program Files (x86)\\app\\IDEA\\IDEA_WORKE\\sa-token-demo\\src\\main\\resources\\templates/result/日志.docx";
        String imagePath = "D:\\Program Files (x86)\\app\\IDEA\\IDEA_WORKE\\sa-token-demo\\src\\main\\resources\\templates\\templates\\hyaqweb.jpg";
        try {
            // 读取模板文件
            FileInputStream inputStream = new FileInputStream(templatePath);
            XWPFDocument document = new XWPFDocument(inputStream);

            // 替换文本
            //replaceText(document, "${placeholder}", replacementText);
            wordReplaceText(document);

            // 插入图片
            //insertImage(document, imagePath);

            // 保存输出文件
            FileOutputStream outputStream = new FileOutputStream(outputPath);
            document.write(outputStream);

            // 关闭流
            outputStream.close();
            inputStream.close();
            document.close();

            System.out.println("操作完成！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void wordReplaceText(XWPFDocument doc){
        Map<String, String> map = new HashMap<>();
        map.put("${year}", "2023");
        map.put("${month}", "07");
        map.put("${day}", "27");
        map.put("${planName}", "测试计划");
        map.put("${tractorNumber}", "陕AA789Q");
        map.put("${route}", "西安-渭南");
        map.put("${comsuerName}", "陕西天地众力能源发展有限公司华州区分公司");

        replaceText(doc,map);
    }

    private static void replaceText(XWPFDocument doc, String findText, String replaceText) {
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null && text.contains(findText)) {
                    text = text.replace(findText, replaceText);
                    run.setText(text, 0);
                }
            }
        }
    }
    private static void replaceText(XWPFDocument doc, Map<String, String> map) {
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                for (String key : map.keySet()) {
                    System.out.println("key = " + key);
                    if (text != null && text.contains(key)) {
                        String value = map.get(key);
                        text = text.replace(key, value);
                        run.setText(text, 0);
                    }
                }

            }
        }
    }

    private static void insertImage(XWPFDocument doc, String imagePath) {
        try {
            File imageFile = new File(imagePath);
            FileInputStream imageStream = new FileInputStream(imageFile);
            byte[] imageBytes = IOUtils.toByteArray(imageStream);
            imageStream.close();

            int format;
            if (imagePath.endsWith(".png")) {
                format = XWPFDocument.PICTURE_TYPE_PNG;
            } else if (imagePath.endsWith(".jpg") || imagePath.endsWith(".jpeg")) {
                format = XWPFDocument.PICTURE_TYPE_JPEG;
            } else {
                throw new IllegalArgumentException("Unsupported image file format.");
            }

            try {
                doc.createParagraph().createRun().addPicture(
                        new ByteArrayInputStream(imageBytes), format, imageFile.getName(), Units.toEMU(200), Units.toEMU(200)
                );
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

